package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SM3;
import com.ruoyi.common.utils.SM4;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.config.ApiConfig;
import com.ruoyi.system.domain.SysFileRsp;
import com.ruoyi.system.mapper.SysFileRspMapper;
import com.ruoyi.system.service.ISysFileRspService;
import com.ruoyi.system.service.ISysFileService;
import com.ruoyi.system.utils.HttpApi;
import com.ruoyi.system.utils.ParametricTask;
import com.ruoyi.system.utils.TaskScheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Validator;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 中移接口返回Service业务层处理
 *
 * @author ruoyi
 * @date 2025-01-15
 */
@Service
public class SysFileRspServiceImpl implements ISysFileRspService {
    private static final Logger log = LoggerFactory.getLogger(SysFileRspServiceImpl.class);
    @Autowired
    protected Validator validator;
    @Autowired
    private SysFileRspMapper sysFileRspMapper;
    @Autowired
    private ISysFileService sysFileService;
    @Autowired
    private ApiConfig apiConfig;


    /**
     * 查询中移接口返回
     *
     * @param empowerNo 中移接口返回主键
     * @return 中移接口返回
     */
    @Override
    public SysFileRsp selectSysFileRspByEmpowerNo(String empowerNo) {
        return sysFileRspMapper.selectSysFileRspByEmpowerNo(empowerNo);
    }

    /**
     * 查询中移接口返回列表
     *
     * @param sysFileRsp 中移接口返回
     * @return 中移接口返回
     */
    @Override
    public List<SysFileRsp> selectSysFileRspList(SysFileRsp sysFileRsp) {
        return sysFileRspMapper.selectSysFileRspList(sysFileRsp);
    }

    @Override
    public int saveMobile(String mobile, Long fileId) {
        String s = IdUtils.fastSimpleUUID().substring(1);
        SysFileRsp rsp = new SysFileRsp();
        rsp.setFileId(fileId);
        rsp.setMobile(mobile);
        rsp.setEmpowerNo(s);
        JSONObject of = JSONObject.of("mobile", SM3.encrypt(mobile),
                "empowerNo", s);
//        Base64.Encoder encoder = Base64.getEncoder();
//        String param = encoder.encodeToString(of.toJSONString().getBytes(StandardCharsets.UTF_8));
        log.info("请求参数 - of:{} ", JSONObject.of("param", of));
        String param = JSONObject.of("param", of).toJSONString();
        log.info("请求参数 - param:{} ", param);
        String gfyy = HttpApi.sendSSLApi(apiConfig.getGfyy(), s + "A", apiConfig.getSecretid(), apiConfig.getSecretkey(), apiConfig.getUrl(), param);
        log.info("返回结果 -gfyy:{}", gfyy);
        String fdcyxjz = HttpApi.sendSSLApi(apiConfig.getFdcyxjz(), s + "B", apiConfig.getSecretid(), apiConfig.getSecretkey(), apiConfig.getUrl(), param);
        log.info("返回结果 -fdcyxjz:{}", fdcyxjz);
        JSONObject js1 = JSONObject.parseObject(gfyy);
        JSONObject js2 = JSONObject.parseObject(fdcyxjz);

        SysFileRsp sysFileRsp = new SysFileRsp();
        sysFileRsp.setFileId(fileId);
        sysFileRsp.setMobile(mobile);
        sysFileRsp.setEmpowerNo(s);
        try {
            String responseCode1 = js1.getJSONObject("head").getString("responseCode");
            log.info("responseCode1:{};{}", responseCode1, "0000".equals(responseCode1));
            if ("0000".equals(responseCode1)) {
                String response = js1.getString("response");
                String decrypt = SM4.decrypt(response, apiConfig.getSecretkey());
                Object response1 = js1.put("response", decrypt);
                log.info("decrypt:{} response1 - {}", decrypt, js1);
                sysFileRsp.setGfyyResponse(decrypt);
                String gfyy_score = JSONObject.parseObject(decrypt).getString("gfyy_score");
                sysFileRsp.setGfyyScore(gfyy_score);
            } else {
                sysFileRsp.setGfyyResponse(gfyy);
            }

            String responseCode2 = js2.getJSONObject("head").getString("responseCode");
            log.info("responseCode2:{};{}", responseCode2, "0000".equals(responseCode2));
            if ("0000".equals(responseCode2)) {
                String response = js2.getString("response");
                String decrypt = SM4.decrypt(response, apiConfig.getSecretkey());
                Object response2 = js2.put("response", decrypt);
                log.info("decrypt:{} js1 - {}", decrypt, js2);
                sysFileRsp.setFdcyxjzResponse(decrypt);
                String fdcyxjz_score = JSONObject.parseObject(decrypt).getString("fdcyxjz_score");
                sysFileRsp.setFdcyxjzScore(fdcyxjz_score);
            } else {
                sysFileRsp.setFdcyxjzResponse(fdcyxjz);
            }
        } catch (Exception e) {
            log.error("解密返回值异常", e);
        }

        return insertSysFileRsp(sysFileRsp);
    }

    /**
     * 新增中移接口返回
     *
     * @param sysFileRsp 中移接口返回
     * @return 结果
     */
    @Override
    public int insertSysFileRsp(SysFileRsp sysFileRsp) {
        return sysFileRspMapper.insertSysFileRsp(sysFileRsp);
    }

    /**
     * 修改中移接口返回
     *
     * @param sysFileRsp 中移接口返回
     * @return 结果
     */
    @Override
    public int updateSysFileRsp(SysFileRsp sysFileRsp) {
        return sysFileRspMapper.updateSysFileRsp(sysFileRsp);
    }

    /**
     * 批量删除中移接口返回
     *
     * @param empowerNos 需要删除的中移接口返回主键
     * @return 结果
     */
    @Override
    public int deleteSysFileRspByEmpowerNos(String[] empowerNos) {
        return sysFileRspMapper.deleteSysFileRspByEmpowerNos(empowerNos);
    }

    /**
     * 删除中移接口返回信息
     *
     * @param empowerNo 中移接口返回主键
     * @return 结果
     */
    @Override
    public int deleteSysFileRspByEmpowerNo(String empowerNo) {
        return sysFileRspMapper.deleteSysFileRspByEmpowerNo(empowerNo);
    }

    /**
     * 导入用户数据
     *
     * @param userList      用户数据列表
     * @param updateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param fileId      操作用户
     * @return 结果
     */

    @Override
    public String importPhone(List<SysFileRsp> userList, boolean updateSupport, Long fileId) {

        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (SysFileRsp user : userList) {
            String mobile = user.getMobile();
            try {
                // 验证是否存在这个用户

                if (StringUtils.isNotBlank(mobile)) {
                    BeanValidators.validateWithException(validator, user);
                    int i = saveMobile(user.getMobile(), fileId);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、手机号 " + mobile + " 导入成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、手机号 " + mobile + " 为空");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、手机号 " + mobile + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


    /**
     * 导入用户数据
     *
     * @param userList      用户数据列表
     * @param fileId      操作用户
     * @return 结果
     */
    @Override
    public String importPhone(List<SysFileRsp> userList, Long fileId) {

        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (SysFileRsp user : userList) {
            String mobile = user.getMobile();
            try {
                // 验证是否存在这个用户

                if (StringUtils.isNotBlank(mobile)) {
                    BeanValidators.validateWithException(validator, user);

                    SysFileRsp sysFileRsp = new SysFileRsp();
                    sysFileRsp.setFileId(fileId);
                    sysFileRsp.setMobile(mobile);
                    sysFileRsp.setEmpowerNo(IdUtils.fastSimpleUUID());
                    int i = insertSysFileRsp(sysFileRsp);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、手机号 " + mobile + " 导入成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、手机号 " + mobile + " 为空");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、手机号 " + mobile + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public String uploadData(MultipartFile file, Long fileId) {
        String s = IdUtils.fastSimpleUUID();
        JSONObject head = HttpApi.generateHead(s, apiConfig.getSecretid(), apiConfig.getSecretkey());
        JSONObject request = JSONObject.of("apis", Arrays.asList("AME000964", "AME000965"), "files", file);
        String batchResponse = HttpApi.sendCommonSSLApi("batch/submit", apiConfig.getUrl(), "multipart/form-data", head, request);
        log.info("batch/submit -> batchResponse:{}", batchResponse);
        JSONObject js1 = JSONObject.parseObject(batchResponse);
        String requestId = js1.getString("requestId");
        // 延时队列查询结果
        return getTaskStatus(requestId, fileId);
    }

    @Autowired
    private TaskScheduler taskScheduler;
    private String getTaskStatus(String requestId, Long fileId) {
        // 查询任务状态
        taskScheduler.submit(new ParametricTask(requestId, fileId), 30, TimeUnit.MINUTES);
        return requestId;
    }


}
